<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限 - 只有管理员可以访问
if (!$current_user || $current_user['role'] !== 'admin') {
    header('Location: /POS/index.php');
    exit;
}

// 处理操作
$action = $_GET['action'] ?? '';
$product_id = $_GET['id'] ?? 0;

// 处理商品添加
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    $name = $_POST['name'] ?? '';
    $category_id = $_POST['category_id'] ?? 0;
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
    $cost_price = isset($_POST['cost_price']) ? floatval($_POST['cost_price']) : 0;
    $description = $_POST['description'] ?? '';
    $status = $_POST['status'] ?? 'active';
    
    // 验证商品名称是否已存在
    $check_sql = "SELECT id FROM products WHERE name = ?";
    $existing_product = Database::fetch($check_sql, [$name]);
    
    if ($existing_product) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该商品名称已存在'
        ];
    } else {
        // 处理图片上传
        $image_path = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads/products/';
            
            // 如果目录不存在则创建
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '.' . $file_extension;
            $upload_file = $upload_dir . $filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_file)) {
                $image_path = '/uploads/products/' . $filename;
            }
        }
        
        // 插入新商品
        $sql = "INSERT INTO products (name, category_id, price, description, image, status, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW())";
        $result = Database::query($sql, [$name, $category_id, $price, $description, $image_path, $status]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '商品添加成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '商品添加失败'
            ];
        }
    }
    
    // 重定向到商品列表
    header('Location: /POS/products_manage.php');
    exit;
}

// 处理商品编辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'edit' && $product_id) {
    $name = $_POST['name'] ?? '';
    $category_id = $_POST['category_id'] ?? 0;
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
    $description = $_POST['description'] ?? '';
    $status = $_POST['status'] ?? 'active';
    
    // 检查商品名称是否被其他商品使用
    $check_sql = "SELECT id FROM products WHERE name = ? AND id != ?";
    $existing_product = Database::fetch($check_sql, [$name, $product_id]);
    
    if ($existing_product) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该商品名称已被其他商品使用'
        ];
    } else {
        // 处理图片上传
        $image_sql = '';
        $image_params = [$name, $category_id, $price, $description, $status, $product_id];
        
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads/products/';
            
            // 如果目录不存在则创建
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '.' . $file_extension;
            $upload_file = $upload_dir . $filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_file)) {
                $image_path = '/uploads/products/' . $filename;
                $image_sql = ', image = ?';
                array_splice($image_params, -1, 0, [$image_path]); // 在最后一个参数前插入图片路径
            }
        }
        
        // 更新商品信息
        $sql = "UPDATE products SET name = ?, category_id = ?, price = ?, description = ?, status = ? $image_sql WHERE id = ?";
        $result = Database::query($sql, $image_params);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '商品信息更新成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '商品信息更新失败'
            ];
        }
    }
    
    // 重定向到商品列表
    header('Location: /POS/products_manage.php');
    exit;
}

// 处理商品删除
if ($action === 'delete' && $product_id) {
    // 检查商品是否有关联订单
    $check_sql = "SELECT COUNT(*) FROM order_items WHERE product_id = ?";
    $order_count = Database::fetchColumn($check_sql, [$product_id]);
    
    if ($order_count > 0) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该商品有关联订单，无法删除，您可以将其状态设为停用'
        ];
    } else {
        // 删除商品
        $sql = "DELETE FROM products WHERE id = ?";
        $result = Database::query($sql, [$product_id]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '商品删除成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '商品删除失败'
            ];
        }
    }
    
    // 重定向到商品列表
    header('Location: /POS/products_manage.php');
    exit;
}

// 查询单个商品信息（用于编辑）
$product = null;
if ($action === 'edit' && $product_id) {
    $sql = "SELECT * FROM products WHERE id = ?";
    $product = Database::fetch($sql, [$product_id]);
    
    if (!$product) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '商品不存在'
        ];
        header('Location: /POS/products_manage.php');
        exit;
    }
}

// 获取所有分类列表
$sql = "SELECT * FROM categories ORDER BY name";
$categories = Database::fetchAll($sql);

// 获取商品列表
$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 构建查询条件
$where = [];
$params = [];

if ($search) {
    $where[] = "(products.name LIKE ? OR products.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($category_filter) {
    $where[] = "products.category_id = ?";
    $params[] = $category_filter;
}

if ($status_filter) {
    $where[] = "products.status = ?";
    $params[] = $status_filter;
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// 查询商品总数
$count_sql = "SELECT COUNT(*) FROM products $where_clause";
$total = Database::fetchColumn($count_sql, $params);
$total_pages = ceil($total / $per_page);

// 查询商品列表
$sql = "SELECT products.*, categories.name as category_name 
        FROM products 
        LEFT JOIN categories ON products.category_id = categories.id 
        $where_clause 
        ORDER BY products.name ASC 
        LIMIT $offset, $per_page";
$products = Database::fetchAll($sql, $params);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">商品管理</h1>
            <p class="text-muted">查看和管理所有商品</p>
        </div>
        <div class="col-md-6 text-md-right">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addProductModal">
                <i class="fas fa-plus-circle"></i> 添加商品
            </button>
        </div>
    </div>
    
    <!-- 过滤和搜索 -->
    <div class="card mb-4">
        <div class="card-body">
            <form action="" method="GET" class="row">
                <div class="col-md-4 mb-3 mb-md-0">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" name="search" placeholder="商品名称/描述" value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-md-3 mb-3 mb-md-0">
                    <select name="category" class="form-control">
                        <option value="">全部分类</option>
                        <?php foreach ($categories as $category): ?>
                        <option value="<?php echo $category['id']; ?>" <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($category['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 mb-3 mb-md-0">
                    <select name="status" class="form-control">
                        <option value="">全部状态</option>
                        <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>启用</option>
                        <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>停用</option>
                    </select>
                </div>
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary btn-block">筛选</button>
                </div>
                <div class="col-md-2">
                    <a href="/POS/products_manage.php" class="btn btn-secondary btn-block">重置</a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 商品列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图片</th>
                            <th>商品名称</th>
                            <th>分类</th>
                            <th>售价</th>
                            <th>成本价</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($products)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">没有找到相关商品</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($products as $p): ?>
                        <tr>
                            <td><?php echo $p['id']; ?></td>
                            <td>
                                <?php if (!empty($p['image'])): ?>
                                <img src="<?php echo htmlspecialchars($p['image']); ?>" alt="<?php echo htmlspecialchars($p['name']); ?>" class="product-thumbnail">
                                <?php else: ?>
                                <div class="no-image">暂无图片</div>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($p['name']); ?></td>
                            <td><?php echo htmlspecialchars($p['category_name'] ?? '未分类'); ?></td>
                            <td><?php echo number_format($p['price'], 2); ?> 元</td>
                            <td><?php echo number_format($p['cost_price'], 2); ?> 元</td>
                            <td>
                                <?php if ($p['status'] === 'active'): ?>
                                <span class="badge badge-success">启用</span>
                                <?php else: ?>
                                <span class="badge badge-secondary">停用</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="/POS/products_manage.php?action=edit&id=<?php echo $p['id']; ?>" class="btn btn-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="#" onclick="confirmDelete(<?php echo $p['id']; ?>); return false;" class="btn btn-danger">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 添加商品模态框 -->
<div class="modal fade" id="addProductModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form action="/POS/products_manage.php?action=add" method="POST" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title">添加新商品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>商品名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                            <div class="form-group">
                                <label>分类</label>
                                <select name="category_id" class="form-control">
                                    <option value="0">未分类</option>
                                    <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo $category['id']; ?>">
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>售价 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">¥</span>
                                    </div>
                                    <input type="number" class="form-control" name="price" min="0" step="0.01" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>成本价</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">¥</span>
                                    </div>
                                    <input type="number" class="form-control" name="cost_price" min="0" step="0.01" value="0">
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>商品图片</label>
                                <input type="file" class="form-control-file" name="image" accept="image/*">
                                <small class="form-text text-muted">推荐尺寸：300x300像素，最大文件大小：2MB</small>
                            </div>
                            <div class="form-group">
                                <label>商品描述</label>
                                <textarea class="form-control" name="description" rows="3"></textarea>
                            </div>
                            <div class="form-group">
                                <label>状态</label>
                                <select name="status" class="form-control">
                                    <option value="active">启用</option>
                                    <option value="inactive">停用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑商品表单 -->
<?php if ($action === 'edit' && $product): ?>
<div class="container-fluid mt-4">
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">编辑商品信息</h5>
        </div>
        <div class="card-body">
            <form action="/POS/products_manage.php?action=edit&id=<?php echo $product['id']; ?>" method="POST" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>商品名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($product['name']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>分类</label>
                            <select name="category_id" class="form-control">
                                <option value="0">未分类</option>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>" <?php echo $product['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($category['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>售价 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">¥</span>
                                </div>
                                <input type="number" class="form-control" name="price" min="0" step="0.01" value="<?php echo htmlspecialchars($product['price']); ?>" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>成本价</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">¥</span>
                                </div>
                                <input type="number" class="form-control" name="cost_price" min="0" step="0.01" value="<?php echo htmlspecialchars($product['cost_price']); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>当前图片</label>
                            <?php if (!empty($product['image'])): ?>
                            <div class="mb-2">
                                <img src="<?php echo htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" class="img-thumbnail" style="max-height: 150px;">
                            </div>
                            <?php else: ?>
                            <div class="mb-2">暂无图片</div>
                            <?php endif; ?>
                            <input type="file" class="form-control-file" name="image" accept="image/*">
                            <small class="form-text text-muted">上传新图片将替换现有图片。建议尺寸：300x300像素，最大文件大小：2MB</small>
                        </div>
                        <div class="form-group">
                            <label>商品描述</label>
                            <textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($product['description']); ?></textarea>
                        </div>
                        <div class="form-group">
                            <label>状态</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo $product['status'] === 'active' ? 'selected' : ''; ?>>启用</option>
                                <option value="inactive" <?php echo $product['status'] === 'inactive' ? 'selected' : ''; ?>>停用</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group mt-3">
                    <a href="/POS/products_manage.php" class="btn btn-secondary">返回列表</a>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- 自定义样式 -->
<style>
.product-thumbnail {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 4px;
}
.no-image {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f0f0f0;
    color: #999;
    font-size: 10px;
    border-radius: 4px;
    text-align: center;
}
</style>

<script>
// 删除确认
function confirmDelete(productId) {
    if (confirm('确定要删除此商品吗？此操作不可恢复！')) {
        window.location.href = '/POS/products_manage.php?action=delete&id=' + productId;
    }
}

// 显示提示消息
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['alert'])): ?>
    showAlert('<?php echo $_SESSION['alert']['message']; ?>', '<?php echo $_SESSION['alert']['type']; ?>');
    <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 